<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 罐箱配件采购申请
 *
 */
class XStockbuy extends Backend
{
    /**
     * XStockbuy模型对象
     * @var \app\admin\model\XStockbuy
     */
    protected $model = null;
    
    protected $quickSearchField = ['BIZNO'];

    protected $defaultSortField = 'BIZNO,desc';

    protected $preExcludeFields = [''];
    protected $noNeedLogin      = ['*'];
    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XStockbuy;
    }
    /**
     * 报价
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        $status='';
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        foreach ($where as $k=>$item) {
            if(in_array('x_stockbuy.status',$item)){
                $status=" dbo.f_getflowstatus(BIZNO) = '$item[2]'";
                unset($where[$k]);
            }
        }

        $m='';
        $adminInfo          = $this->auth->getInfo();
        $name='';
        if($adminInfo['id']!=1){
            $name='x_stockbuy.OP='.$adminInfo['nickname'];
        }
        $res = $this->model
            ->field(['x_stockbuy.*,dbo.f_getflowstatus(BIZNO) as status,DEPARTMENT.DEPTNAME'])
            ->join('DEPARTMENT',"x_stockbuy.DEPT=DEPARTMENT.DEPTID")
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($status)
            ->where($where)
//            ->where($m)
            ->where($name)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $adminInfo          = $this->auth->getInfo();
            $data['OP']=$adminInfo['nickname'];
            $data['OPTIME']=date('Y-m-d H:i:s',time());
            $data['SQR']=$adminInfo['nickname'];
            $data['DEPT']=$adminInfo['department'];
            $data['SQDATE']=date('Y-m-d H:i:s',time());
            $data['BIZNO']='PJ'. $this->microtime_format('YmdHisx',$this->microtime_float());
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'),  $this->model->BIZNO);
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
    /**
     * 配件申请提交审批
     */
    public function tj(){
        $post=$this->request->get();
        $adminInfo          = $this->auth->getInfo();
        //查出部门
        $dep=$this->model->where('BIZNO',$post['bizno'])->find();
        $s= $this->createflowdata($post['bizno'],$dep['DEPT'],'配件审批',$dep['PRICE']);
        if($s==200){
            $this->success('提交成功');
        }else{
            $this->error('提交失败');
        }

    }
    /**
     * 审批
     */
    public function index_s()
    {

        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $status='';
        $adminInfo          = $this->auth->getInfo();
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $m='';
        if($adminInfo['id']!=1){
            if(empty($where)){
                $m="dbo.f_getflowstatus(BIZNO) != '已完成' and exists ( select * from u_flowdata where u_flowdata.bizno=x_stockbuy.BIZNO   and iscurrent=1 and username='$adminInfo[nickname]') ";
            }
            else{
                $m="exists ( select * from u_flowdata where u_flowdata.bizno=x_stockbuy.BIZNO    and username='$adminInfo[nickname]') ";
            }
        }

        foreach ($where as $k=>$item) {
            if(in_array('x_stockbuy.status',$item)){
                $status=" dbo.f_getflowstatus(BIZNO) = '$item[2]'";
                unset($where[$k]);
            }
        }



        $res = $this->model
            ->field(['x_stockbuy.*,dbo.f_getflowstatus(BIZNO) as status,DEPARTMENT.DEPTNAME'])
            ->join('DEPARTMENT',"x_stockbuy.DEPT=DEPARTMENT.DEPTID")
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($status)
            ->where($where)
            ->where($m)
//            ->where('x_stockbuy.OP',$adminInfo['nickname'])
            ->order($order)
//            ->fetchSql()->select();
            ->paginate($limit);
//var_dump($res);die;
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->field('*,dbo.f_getflowstatus(BIZNO) as status')->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row
        ]);
    }
}